import { getChildren } from '@/utils';
import { v4 as uuidv4 } from 'uuid';

interface Layer {
  type: string; // 图层类型
  id: string; // 图层编号
  title: string; // 图层名称
  parent: string; // 父级图层
  enable: boolean; // 是否启用
  order?: number; // 图层排序
  zIndex?: number; // 图层层级
  x: number;
  y: number;
  w: number;
  h: number;
  active: boolean;
  data: Record<string, any>; // 图层数据
}

export default function usePanelLayer() {
  const layers = ref<Layer[]>([]); // 图层列表
  const layerId = ref<string>(''); // 当前选中图层
  const layerData = ref<any>({}); // 当前选中图层的数据

  // 初始化
  const init = (newLayers: Layer[]) => {
    layers.value = newLayers || [];
  };

  // 添加图层
  const addLayer = (layer: Pick<Layer, 'type' | 'w' | 'h' | 'data'> & Partial<Layer>) => {
    const id = uuidv4();
    const defaultLayer = {
      id,
      title: '',
      parent: '',
      x: 0,
      y: 0,
      enable: true,
      active: false,
    };

    layerId.value = id;
    layers.value.push({ ...defaultLayer, ...layer });
  };

  // 删除图层
  const removeLayer = (layerId: string) => {
    const layerIdList = getChildren(layers.value, layerId);
    layers.value = layers.value.filter((layer) => !layerIdList.includes(layer.id));
  };

  // 更新图层
  const updateLayer = (newLayer: Layer) => {
    layers.value.forEach((layer) => {
      if (layer.id === newLayer.id) {
        Object.assign(layer, newLayer);
      }
    });
  };

  // layers、layerId 更新时，更新 layerData
  watch([layers, layerId], () => {
    const currentLayer = layers.value?.find((layer) => layer.id === layerId.value);
    layerData.value = currentLayer || {};
  });

  return {
    layers,
    layerId,
    layerData,
    init,
    addLayer,
    removeLayer,
    updateLayer,
  };
}
